blog

Home / DeveloperSection / Blogs / Implement Ajax Login in ASP.NET MVC

Implement Ajax Login in ASP.NET MVC

Anonymous User22498 28-Feb-2015

In this blog I’m demonstrate how Ajax login can be implemented using jQuery $.ajax (). Implementing Ajax based login involves many of the same steps as the normal forms authentication. However, the login page doesn't send user ID and password to the server through a standard form submission. Instead, user credentials are sent to the server via an Ajax request. The credentials are then validated on the server and the result of the verification process is conveyed to the client. If the login attempt was successful, the user is taken to the secured area of the website.

Let's understand how all this works by developing a sample application. Begin by creating a new ASP.NET MVC Web Application using an empty template. To keep things simple we will add only those things to the project that are absolutely essential to the functioning of this example.

Step 1: Open visual studio >> File >> New Project >> ASP.NET MVC Web Application

Implement Ajax Login in ASP.NET MVC

Give the application name in my sample Name “LoginManage” and click ok.

After click ok open a window and you select project type in this sample I have select “Empty” template.

Implement Ajax Login in ASP.NET MVC

Now our application is stand successfully.

Step 2: Now we have to make database and table

CREATE TABLE Login
(
                Id INT IDENTITY(1,1)PRIMARY KEY,
                Name VARCHAR(100),
                Password VARCHAR(20)
)

 

And insert some dummy data in this table.

Step 3:  Now our need to configure database. This is done with help of .edmx file for use code first approach. Learn more about Code first Approach.

 

Step 4: Create Account Controller and Login View

Then add a controller to the Controllers folder - AccountController. The Account controller contains code that validates a user. The Login () and ValidateUser () action methods of the Account controller are shown below:

 

AccountController:

 

publicclassAccountController : Controller
    {
        //
        // GET: /Account/
 
        MyDBEntities db = newMyDBEntities();
 
        publicActionResult Login()
        {
            return View();
        }
        [HttpPost]
        publicJsonResult ValidateUser(string userid, string password)
        {
            var data = from c in db.Logins where c.Name == userid && c.Password == password select c;
            if (data.Count()>0)
                return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
            else
                return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
        }
    }

 

The Login () action method simply returns the Login view. The ValidateUser () method is important to us because this method validates the user credentials and is called via Ajax. The ValidateUser () method takes two parameter – userid and password. Inside, inside ValidateUser () method execute a query for user is validate or not correct. The Login class looks like this:

publicpartialclassLogin
{
        publicint Id { get; set; }
        publicstring Name { get; set; }
        publicstring Password { get; set; }
 }

 

The Login class consists of three properties - Id, Name, and Password. The Id property holds user id that is unique. The Name property holds a Username. The password property holds the user password.

 
Login View:

 

<divclass="container">
    <divclass="row">
        <divclass="col-md-6 col-md-offset-3 alert alert-warning">
            <h2class="text-center">Login</h2>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="form-group">
                        <divclass="input-group">
                            <spanclass="input-group-addon"><iclass="glyphicon glyphicon-user"></i></span>
                            <inputtype="text"id="userid"class="form-control"placeholder="Username">
                        </div>
                    </div>
                </div>
            </div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="form-group">
                        <divclass="input-group">
                            <spanclass="input-group-addon"><iclass="glyphicon glyphicon-lock"></i></span>
                            <inputtype="password"class="form-control"id="password"placeholder="Password">
                        </div>
                    </div>
                </div>
            </div>
            <divclass="row">
                <divclass="col-md-12">
                    <divclass="form-group">
                        <buttonclass="btn btn-warning form-control"type="submit"id="savedata"><iclass="glyphicon glyphicon-log-in"></i>&nbsp;Login</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

 

Implement Ajax Login in ASP.NET MVC

 

The Login view consists of a textbox, a password box, and a button. Clicking on the Login button initiates an Ajax request to the ValidateUser () method you created earlier. The jQuery code responsible for calling the ValidateUser () method is given below:

 
<script>
    $(document).ready(function () {
        $('#savedata').click(function () {
            var data = {
                "userid": $("#userid").val(),
                "password": $("#password").val()
            };
            $.ajax({
                url: "/Account/validateuser",
                type: "POST",
                data: JSON.stringify(data),
                dataType: "json",
                contentType: "application/json",
                success: function (response) {
                    if (response.Success) {
                        $.get("@Url.Action("Index", "Home")", function (data) {
                            $('.container').html(data);
                        });
                      
                    }
                    else
                        window.location.href = "@Url.Action("Login", "Account")";
                },
                error: function () {
                    console.log('Login Fail!!!');
                }
            });
        });
    });
</script>

 

The code then forms a JavaScript object that has three properties – userid and password. These property names must match the parameter names of the ValidateUser () action method you created earlier. Then $.ajax () of jQuery is used to make an Ajax request to /account/validateuser. The type of the request is set to POST. The data setting contains the stringified version of the data JavaScript object you just created. The dataType and contentType properties are set to json and application/json respectively. These two properties represent the response format and the request MIME content type respectively. The success function receives a status object. This object is a JSON representation of Login object you return from the ValidateUser () method. If the Success property is true it means that the login attempt was successful and the user is redirected to the Home Controller using window.location.href property. If the login attempt fails that time user redirect Account Controller Login Action. The error function is invoked if there is any error making the Ajax call and simply displays an error message to the user.

The following figure shows the login view in action:

 

Implement Ajax Login in ASP.NET MVC

 

Step 5:  Create Home controller and Index view

 

If a login attempt is successful the user is taken to the Index view. So, add the Home controller and also the Index view.

 

publicclassHomeController : Controller
{
        //
        // GET: /Home/
 
        publicActionResult Index()
        {
            return View();
        }
 }

 

The index view contains the simple welcome message.

 

@{
    ViewBag.Title = "Index";
}
 
<h2>Welcome in Index Methods</h2>

 

Implement Ajax Login in ASP.NET MVC



in my next post, I'll explain about Render Partial Views in ASP.NET MVC Using Ajax


Updated 22-Feb-2018
I am a content writter !

Leave Comment

Comments

Liked By